package com.scujj.cs6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scujj.cs6.mapper.UserLikeMapper;
import com.scujj.cs6.model.entity.UserLike;
import com.scujj.cs6.service.AnswerService;
import com.scujj.cs6.service.UserLikeService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author FlanChan
 * @description 针对表【user_like】的数据库操作Service实现
 * @createDate 2025-03-25 21:21:24
 */
@Service
@AllArgsConstructor
public class UserLikeServiceImpl extends ServiceImpl<UserLikeMapper, UserLike>
        implements UserLikeService {

    private final static Lock lock = new ReentrantLock();

    private final AnswerService answerService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void likeAnswer(Long id, HttpServletRequest request) {
        try {
            lock.lock();
            Long userId = (Long) request.getAttribute("user");
            if (this.count(new LambdaQueryWrapper<>(UserLike.class).eq(UserLike::getUserId, userId).eq(UserLike::getAnswerId, id)) > 0) {
                throw new RuntimeException("不能重复点赞");
            }
            UserLike userLike = new UserLike();
            userLike.setUserId(userId);
            userLike.setAnswerId(id);
            this.save(userLike);
            // 更新回答点赞数
            answerService.updateLikeCount(id, 1);
        } finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelLikeAnswer(Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        if (this.count(new LambdaQueryWrapper<>(UserLike.class).eq(UserLike::getUserId, userId).eq(UserLike::getAnswerId, id)) == 0) {
            throw new RuntimeException("未点赞");
        }
        this.remove(new LambdaQueryWrapper<>(UserLike.class).eq(UserLike::getUserId, userId).eq(UserLike::getAnswerId, id));
        // 更新回答点赞数
        answerService.updateLikeCount(id, -1);
    }
}




